package com.eric.ipc.binder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.eric.ipc.R;

public class BinderActivity extends Activity implements OnClickListener{
   private Button mPlayBtn;
   private Button mStopBtn;
   private Button mExitBtn;
   private TextView mShowText;
   private IBinder mIBinder;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.binder_layout);
        
        mPlayBtn = (Button)findViewById(R.id.play);
        mStopBtn = (Button)findViewById(R.id.stop);
        mExitBtn = (Button)findViewById(R.id.exit);
        mShowText = (TextView)findViewById(R.id.show);
        
        mPlayBtn.setOnClickListener(this);
        mStopBtn.setOnClickListener(this);
        mExitBtn.setOnClickListener(this);
        
        Intent intent = new Intent("com.eric.ipc.binder");
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        
        mShowText.setText("binder achieve");
    }
    private ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.e("XXX", "onServiceDisconnected");
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mIBinder = service;
			Log.e("XXX", "onServiceConnected");
		}
	};
	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.play:
				Parcel send_data = Parcel.obtain();
				send_data.writeString("play");
				Parcel reply_data = Parcel.obtain();
				try {
					mIBinder.transact(1, send_data, reply_data, 0);
					mShowText.setText(reply_data.readString());
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				break;
			case R.id.stop:
				Parcel send_data2 = Parcel.obtain();
				send_data2.writeString("stop");
				Parcel reply_data2 = Parcel.obtain();
				try {
					mIBinder.transact(2, send_data2, reply_data2, 0);
					mShowText.setText(reply_data2.readString());
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				break;
			case R.id.exit:
				unbindService(mServiceConnection);
				stopService(new Intent("com.eric.ipc.binder"));
				finish();
				break;
			default :
				break;
		}
	}
}